/**
 * grayrabbit Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package com.grayrabbit.slacker.gengerate;

import java.util.Map;

import com.grayrabbit.slacker.config.GenerateConfig;
import com.grayrabbit.slacker.constant.PropertyConsant;
import com.grayrabbit.slacker.interfaces.CodeGenerate;
import com.grayrabbit.slacker.utils.TemplateProcessUtils;

/**
 * 
 * @author liyd
 * @version $Id: ActionValidationXmlGenerate.java, v 0.1 2012-5-25 下午4:00:56 liyd Exp $
 */
public class ActionValidationXmlGenerate extends NormalGenerate implements CodeGenerate {

    /** 
     * @see com.grayrabbit.slacker.interfaces.CodeGenerate#generate(com.grayrabbit.slacker.config.GenerateConfig, java.util.Map)
     */
    public void generate(GenerateConfig generateConfig, Map<String, String> modelMap) {
        super.normalDataInit(generateConfig);

        //不包含包名
        String actionClassName = this.getClassName(ACTION_QUALIFIED_CLASS_NAME);

        //模板文件夹
        String templateDir = TemplateProcessUtils.getTargetDirPath(generateConfig);

        String templateName = getActionName(actionClassName)
                              + TemplateProcessUtils.getEndFix(generateConfig)
                              + TemplateProcessUtils.getSuffix(generateConfig);

        //需要指定生成的文件名，根据action拆分
        generateConfig.setTargetFilePath(templateDir + PropertyConsant.DIR_SEPARATOR
                                         + actionClassName + "-" + templateName);

        StringBuilder validationFieldVm = new StringBuilder();

        //根据属性生成
        for (String[] column : generateConfig.getColumns()) {

            //属性名称
            String propertyName = TemplateProcessUtils.getPropertyName(column[1]);

            validationFieldVm.append(generateValidationField(generateConfig, propertyName));

        }

        modelMap.put("validationField", validationFieldVm.toString());

        modelMap.put("actionName", getActionName(actionClassName));

    }

    /**
     * 
     * 
     * @param generateConfig
     * @param propertyName
     * @return
     */
    private String generateValidationField(GenerateConfig generateConfig, String propertyName) {

        //get set方法模板文件
        String vm = TemplateProcessUtils.getTemplate(generateConfig.getProperties()
            .get(PropertyConsant.TEMPLATE).getChildProperties().get("validationFieldTemplate")
            .getValue());
        vm = vm.replaceAll("\\$\\{entityInstance\\}", TemplateProcessUtils.convertFirstLower(this
            .getClassName(this.ENTITY_QUALIFIED_CLASS_NAME)));
        vm = vm.replaceAll("\\$\\{propertyName\\}", propertyName);

        return vm;
    }

}
